<!--
 * @Author: your name
 * @Date: 2020-10-19 09:03:10
 * @LastEditTime: 2020-10-19 12:59:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \AK-FRONT-5.0e:\demo\vue-datav-chart\src\views\demo\map.vue
-->
<template>
  <div class="wrapper">
    <div ref="myMapRef"
         class="container"></div>
  </div>
</template>
<script>
import { ref, onMounted } from "vue"

export default {
  setup() {
    let polygons = []
    const myMapRef = ref(null) // 定义ref
    const chartMapInit = () => {
      const map = new window.AMap.Map(myMapRef.value, {
        center: [116.30946, 39.937629],
        resizeEnable: true,
        zoom: 3
      })

      map.on("click", (e) => {
        console.log(`您在[ ${e.lnglat.getLng()},${e.lnglat.getLat()} ]的位置点击了地图！`, "resres")
        const geoCoder = new window.AMap.Geocoder({
          city: ""// 城市，默认：“全国”
        })
        const lnglatXY = [
          e.lnglat.getLng(),
          e.lnglat.getLat()
        ] // 地图上所标点的坐标
        let abcde = ""
        let abcdeName = ""
        // 逆解析: 经纬度转地址
        geoCoder.getAddress(lnglatXY, (info, reg) => {
          if (reg.info === "OK") {
            console.log(reg.regeocode, "reg.regeocode")
            abcde = reg.regeocode.addressComponent.adcode
            abcdeName = reg.regeocode.addressComponent.city
            const district = new window.AMap.DistrictSearch({
              subdistrict: 0,
              // 返回行政区边界坐标等具体信息
              extensions: "all",
              // 设置查询行政区级别为 区
              level: "district"
            })
            console.log(abcde, "abcdeabcde")
            district.search(abcdeName, (status, result) => {
              console.log(result, "result")
              map.remove(polygons)// 清除上次结果
              polygons = []
              // 获取边界信息
              const bounds = result.districtList[0].boundaries
              const colors = ["#2c9ea0", "#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00"]
              if (bounds) {
                bounds.forEach((element) => {
                  const index = (Math.random() * 9 + 1).toFixed(0)
                  const strokeColor = colors[index]
                  const polygon = new window.AMap.Polygon({
                    map,
                    strokeWeight: 1,
                    path: element,
                    fillOpacity: 0.7,
                    fillColor: "#109618",
                    strokeColor
                  })
                  polygons.push(polygon)
                })
              }
              map.add(polygons)
              map.setFitView(polygons)// 视口自适应
            })
          }
        })
      })
    }
    onMounted(() => {
      chartMapInit()
    })
    return {
      myMapRef
    }
  }
}
</script>
<style lang="scss" scoped >
.wrapper {
  width: 100vw;
  height: 100vh;
  position: absolute;
  margin: 0;
  padding: 0;
  color: #ffffff;
  .container {
    height: 100vh;
  }
}
</style>
